//
//  BLEWiFiConnectingVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/4/2.
//

#import "BLEWiFiConnectingVC.h"
#import "RHCustomTimer.h"
#import <YYAnimatedImageView.h>
#import <YYImage/YYImage.h>
#import "CBLECenterMnger.h"
#import "CBLEDataParse.h"
#import "BLESetSecretVC.h"
#import "RHLocalSettingTypeModel.h"

@interface BLEWiFiConnectingVC ()
@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, assign) NSInteger count;

@property (nonatomic, strong) QMUILabel *stateLab;

@property (nonatomic, strong) YYAnimatedImageView  *gifImg;

@end

@implementation BLEWiFiConnectingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"连接WiFi".rh_localized;
    [self setupUI];
    [self createCmd];
    self.timer = [RHCustomTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countAction) userInfo:nil repeats:YES];
    
}


-(void)createCmd
{
    NSDictionary *cmdDic = @{
        @"field":@"Ems_WifiCnctSt",
        @"regAddr":@(22),
        @"bitWidth":@(2),
        @"offset":@(0),
        @"isBit":@(1),
        @"cmdType":@(LocalSettingType_EMS)
    };
   
    RHLocalSettingModel *settingModel = [RHLocalSettingModel yy_modelWithJSON:cmdDic];
    self.cmdArray = @[settingModel];
}

-(void)getConnectStatus
{
    [[RHBleCmdManager shareMnger] readDeviceInfoWithCmdModel:[self.cmdArray firstObject]];
    
}

-(void)countAction
{
    if(self.count == 100){
        [self.timer invalidate];
        self.timer = nil;
        [self.gifImg stopAnimating];
        [QMUITips showError:@"连接超时".rh_localized];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        return;
    }
    self.count += 1;
  
    self.stateLab.text = [NSString stringWithFormat:@"%@...(%ld%%)",@"设备连接网络中".rh_localized,self.count];
    [self getConnectStatus];
      
}

-(void)receiveDeviceMsg:(NSNotification*)no
{
    NSDictionary *dic = [no object];
    if(dic.allKeys.count==0)return;
    if (!self.recieveMsg) return;
    NSLog(@"------>收到设备信息:%@",dic);
  
            
    RHLocalSettingModel *cmdModel = [self.cmdArray firstObject];
   
    if(cmdModel.regAddr == [dic[CMD_ADDRESS] integerValue]){
        
        NSData *data = dic[CMD_ADDRESS_VALUE];
        NSString *parse_content = [CBLEDataParse parseData:data settingModel:cmdModel];
        NSLog(@"---->%@ = %@",cmdModel.field,parse_content);
       
        //未连网
        if([parse_content integerValue] == 0){
            
        }
        
        //连接上路由
        if([parse_content integerValue] == 1){
            [self.timer invalidate];
            self.timer = nil;
            BLESetSecretVC *secretVC = [[BLESetSecretVC alloc]init];
            [self.navigationController pushViewController:secretVC animated:YES];
            if (self.connectSuccessBlock) {
                self.connectSuccessBlock();
            }
        }
        
        //连接上云平台
        if([parse_content integerValue] == 2){
            
        }
    }

}



- (void)setupUI{
    kWeakSelf;
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_ACK,receiveDeviceMsg:);
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.backgroundColor = CFTabViewBgColor;
    [self.view addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    UIView *contentView = kView;
    contentView.backgroundColor = CFTabViewBgColor;
    [scrollView addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
        make.width.offset(kUI_WINDOW_W);
    }];
    
    UIImageView *stepImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ble_config_step1"]];
    stepImg.contentMode = UIViewContentModeScaleAspectFit;
    [contentView addSubview:stepImg];
    [stepImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(15);
        make.width.offset(kScaleW(120));
        make.height.offset(40);
        make.centerX.mas_offset(0);
    }];
    
    _gifImg = [[YYAnimatedImageView alloc]initWithImage:[YYImage imageNamed:@"ble_wifi_connecting.gif"]];
    [contentView addSubview:_gifImg];
    [_gifImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(stepImg.mas_bottom).offset(30);
        make.width.mas_offset(kScaleW(279));
        make.height.mas_offset(kScaleW(113));
        make.centerX.mas_offset(0);
    }];
    
    QMUILabel *stateLab = [[QMUILabel alloc]init];
    stateLab.text = @"设备连接网络中".rh_localized;
    stateLab.textColor = kRGB(63, 68, 67);
    stateLab.font = kSYSTEMFONT(16);
    stateLab.numberOfLines = 0;
    stateLab.textAlignment = NSTextAlignmentCenter;
    [contentView addSubview:stateLab];
    self.stateLab = stateLab;
    [stateLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(weakSelf.gifImg.mas_bottom).offset(50);
    }];
    
    QMUILabel *tipsLab = [[QMUILabel alloc]init];
    tipsLab.text = @"整个联网过程中，请保持设备电量充足，保证路由器网络正常".rh_localized;
    tipsLab.textColor = kColorRGBA(63, 68, 67, 0.8);
    tipsLab.font = kSYSTEMFONT(12);
    tipsLab.textAlignment = NSTextAlignmentCenter;
    tipsLab.numberOfLines = 0;
    [contentView addSubview:tipsLab];
    [tipsLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(stateLab.mas_bottom).offset(15);
        make.bottom.mas_offset(-20);
    }];
}




-(void)dealloc
{
    
    [self.timer invalidate];
    self.timer = nil;
}

@end
